package com.lagou.service.code.service.impl;

import com.lagou.common.util.CommonUtils;
import com.lagou.dubbo.service.CodeService;
import com.lagou.service.code.dao.AuthCodeDAO;
import com.lagou.service.code.pojo.AuthCode;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

@Service
@Component
@RefreshScope
public class CodeServiceImpl implements CodeService {

    @Value("${custom.code.length}")
    private Integer codeLength;

    @Value("${custom.code.timeout}")
    private Integer codeTimeout;

    @Autowired
    private AuthCodeDAO authCodeDAO;

    @Override
    public String create(String email) {

        /** 1 生成验证码信息 */
        // 生成验证码
        String code = CommonUtils.generateNumberCode(codeLength);
        // 取得当前时间
        Timestamp createTime = CommonUtils.now();
        // 计算过期时间
        Timestamp expiresTime = CommonUtils.expiresTime(createTime, codeTimeout * 60000L);

        /** 2 保存验证码信息 */
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreateTime(createTime);
        authCode.setExpireTime(expiresTime);
        authCodeDAO.save(authCode);

        // 返回验证码
        return code;
    }

    @Override
    public Integer validate(String email, String code) {

        /** 1 取得验证码信息 */
        AuthCode authCode = authCodeDAO.findFirstByEmailOrderByCreateTimeDesc(email);

        /** 2 检查验证码 */
        // 验证码不存在或者错误的场合，返回1
        if (authCode == null || !code.equals(authCode.getCode())) {
            return 1;
        }
        // 验证码超时的场合，返回2
        else if (authCode.getExpireTime().compareTo(CommonUtils.now()) < 0) {
            return 2;
        }
        // 验证码正确的场合，返回0
        else {
            return 0;
        }
    }
}
